package com.juzipi.demo.service;

import com.juzipi.demo.mapper.CommentRepository;
import com.juzipi.demo.pojo.Comment;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService{


    @Autowired
    private CommentRepository commentRepository;


    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        Sort sort = Sort.by(Sort.Direction.DESC,"creatTime");
        List<Comment> comments = commentRepository.findByBlogIdAndPatentCommentNull(blogId,sort);
        return eachComment(comments);
    }


    @Transactional
    @Override
    public Comment saveComment(Comment comment) {
        Long parentCommentId = comment.getPatentComment().getId();
        if (parentCommentId != -1){
            comment.setPatentComment(commentRepository.getOne(parentCommentId));
        }else {
            comment.setPatentComment(null);
        }
        comment.setCreatTime(new Date());
        return commentRepository.save(comment);
    }


    /**
     * 循环每个顶级的评论节点
     * @param comments
     * @return
     */
    private List<Comment> eachComment(List<Comment> comments){
        List<Comment> commentList = new ArrayList<>();
        for (Comment comment : comments) {
            Comment comment1 = new Comment();
            BeanUtils.copyProperties(comment,comment1);
            commentList.add(comment1);
        }
        //合并评论的各层子代到第一级子代集合中
        combineChildren(commentList);
        return commentList;
    }


    /**
     *
     * @param comments root 根节点，blog 不为空的对象集合
     */
    private void combineChildren(List<Comment> comments){
        for (Comment comment : comments){
            List<Comment> replays = comment.getReplayComments();
            for (Comment replay : replays) {
                //循环迭代，找出子代，存放在 tempReplys 中
                recursively(replay);
            }
            //修改当前节点的reply集合为迭代处理后的集合
            comment.setReplayComments(tempReplys);
            //清除临时存放区
            tempReplys = new ArrayList<>();
        }
    }
    //存放迭代找出的所有子代集合
    private List<Comment> tempReplys = new ArrayList<>();

    /**
     * 递归迭代，剥洋葱
     * @param comment 被递归的对象
     */
    private void recursively(Comment comment) {
        tempReplys.add(comment);
        if (comment.getReplayComments().size()>0){
            List<Comment> replys = comment.getReplayComments();
            for (Comment reply : replys) {
                tempReplys.add(reply);
                if (reply.getReplayComments().size()>0){
                    recursively(reply);
                }
            }
        }
    }
}
